package com.wqh.data.weather.dao;

import com.google.gson.Gson;
import com.wqh.common.constants.RedisConstant;
import com.wqh.common.util.HttpUtils;
import com.wqh.sevice.pojo.WeatherResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

/**
 * @author wanqh
 * @date 2018/02/10 14:42
 * @description:
 */
@Repository
@Slf4j
public class WeatherCollectionDao {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Gson gson;

    public WeatherResponse getWeatherData(String uri){
        String body = null;
        //先查询缓存中是否有数据
        String key = uri;
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        if(redisTemplate.hasKey(key)){
            log.info("Redis Cache Has Data");
            body = ops.get(key);
        }else {
            log.info("Redis Cache Don't Has Data");
            //缓存中没有数据，请求接口，并将数据保存到缓存。
            String result = HttpUtils.get(uri);
            if(result != null ){
                body = result;
            }
            //将数据保存到缓存。一个参数是key ，第二个是保存的value，第三个是有效期，第四个是有效期的单位
            ops.set(key,body,RedisConstant.WEATHER_DATA_TIME_OUT, TimeUnit.SECONDS  );
        }
        WeatherResponse weatherResponse = gson.fromJson(body, WeatherResponse.class);
        return weatherResponse;
    }
}
